package ore.example.pokemoninfo.GUI;

import de.tr7zw.nbtapi.NBTItem;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

public class PokemonUnlockGUI implements Listener {

    private final Player player;
    private final Inventory gui;

    public PokemonUnlockGUI(Player player) {
        this.player = player;
        this.gui = Bukkit.createInventory(null, 9, "§6宝可梦解锁");

        // 中间槽位留给玩家放置宝可梦相片
        ItemStack placeholder = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
        ItemMeta meta = placeholder.getItemMeta();
        meta.setDisplayName("§7放置宝可梦相片");
        placeholder.setItemMeta(meta);
        gui.setItem(4, placeholder);

        // 解锁按钮
        ItemStack unlockButton = new ItemStack(Material.GREEN_WOOL);
        ItemMeta btnMeta = unlockButton.getItemMeta();
        btnMeta.setDisplayName("§a点击解锁");
        List<String> lore = new ArrayList<>();
        lore.add("§7点击可解锁放置的宝可梦相片");
        btnMeta.setLore(lore);
        unlockButton.setItemMeta(btnMeta);
        gui.setItem(8, unlockButton);

        player.openInventory(gui);
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (event.getInventory() != gui) return; // 只处理这个 GUI
        event.setCancelled(true); // 阻止玩家移动物品

        ItemStack clicked = event.getCurrentItem();
        if (clicked == null) return;

        int slot = event.getRawSlot();
        if (slot == 8) { // 点击解锁按钮
            ItemStack target = gui.getItem(4); // 中间槽
            if (target == null || target.getType() == Material.GRAY_STAINED_GLASS_PANE) {
                player.sendMessage("§c请先放入宝可梦相片！");
                return;
            }

            NBTItem nbti = new NBTItem(target);
            if (!nbti.hasKey("pokemon_data")) {
                player.sendMessage("§c这不是有效的宝可梦相片！");
                return;
            }

            if (!nbti.getBoolean("pokemon_locked")) {
                player.sendMessage("§a宝可梦已经解锁，无需重复解锁！");
                return;
            }

            // 执行解锁
            nbti.setBoolean("pokemon_locked", false);

            // 更新 Lore 显示
            ItemMeta meta = target.getItemMeta();
            if (meta != null) {
                List<String> newLore = new ArrayList<>();
                newLore.add("§7等级: §f" + nbti.getInteger("pokemon_level"));
                newLore.add("§a⚡ 已解锁");
                meta.setLore(newLore);
                target.setItemMeta(meta);
            }

            player.getInventory().addItem(nbti.getItem());
            gui.setItem(4, null); // 清空槽位
            player.sendMessage("§a宝可梦相片已成功解锁！");
        }
    }
}
